<?php
/**
 * Created by PhpStorm.
 * User: yuki
 * Date: 2017/6/21
 * Time: 09:07
 * Remark:  权限模块
 */

namespace app\admin\controller;


use app\admin\model\Rolemenu;
use think\Db;
use think\Request;
use think\Validate;
use app\admin\model\Base;
use app\admin\model\Menu;
use app\admin\model\Role;

class Authority extends Basecontroller
{

    // 功能树
        public function menu()
    {
        $sql = "select * from authority_menu where state='1' order by sortlevel,level asc ";
        $list = Db::query($sql);
        $result_tree = $this-> getTreeData($list);
        $this->assign("list", $result_tree);


        $this->assign('breadcrumb', '菜单列表');
        return $this->fetch();
    }

    // 新增功能
    public function addmenu()
    {
        $request = Request::instance();

        $data = $request->param();
        $upmenuid = $data["upid"];
        $upmenuname = $data["upname"];
        $this->assign("upmenuid", $upmenuid);
        $this->assign("upmenuname", $upmenuname);

        //获取顶级菜单
        $sql = "select * from authority_menu where state='1' order by sortlevel,level asc ";
        $list = Db::query($sql);
        $upmenuid_list = $this-> getTreeData($list);


            $this->assign('upmenuid_list', $upmenuid_list);
            $this->assign('breadcrumb', '添加菜单');

            return $this->fetch();

    }

    //编辑功能树
    public function editmenu()
    {
        $request = Request::instance();

        //查看当前的记录
        $data = $request->param();
        $this->assign('id', $data['id']);
        $list = Db::query("select upmenuid,menuname,state,menuurl from authority_menu where id=?", [$data['id']]);

        //获取顶级菜单
        $upmenuid_list = Menu::all(function($query){
            $query->field('id,menuname,upmenuid')->where(['upmenuid'=> 0,'state'=>1]);
        });
        $upmenuid_list = $this-> getTreeData($upmenuid_list);
        //print_r($upmenuid);
        $this->assign('upmenuid_list', $upmenuid_list);

        $this->assign('breadcrumb', '编辑菜单');

        return $this->fetch('addmenu', [
            'upmenuid' => $list[0]['upmenuid'],
            'upmenuname' => $list[0]['menuname'],
            'list' => $list[0]
        ]);
    }




    // 权限列表
    public function rolelist()
    {

        $model = new Role;
        $option["authority_role.state"] = 1;
        $pageQuery = [];
        $list = DB::name('authority_role')
            ->where($option)
            ->order('authority_role.createdate desc')
            ->paginate(false, false, $pageQuery)
            ->each(function($item,$key){
                $count_admin = DB::name('admin')->join("authority_role","admin.roleid=authority_role.id")->where("admin.roleid={$item['id']}")->count();
                $item['count_admin'] = $count_admin;
                return $item;
            });
     //   print_r($list);
        /*$list = $model::all(function($query){
            $query->where("state='1'")->order("sortlevel,level asc");

        });*/

       // $result_tree = $this->getTreeData($list,'tree','rolename','id','uproleid');
        //$this->assign("result_tree", $result_tree);
        $this->assign("list", $list);


        $this->assign('breadcrumb', '权限列表');
        return $this->fetch();
    }


    // 新增角色
    public function addrole()
    {
        $request = Request::instance();

            $data = $request->param();
            $uproleid = $data["upid"];
            $uprolename = '';
            if ($uproleid != 0) {
                $uprolename = $data["upname"] ? $data["upname"] : '';
            }
            $this->assign("uproleid", $uproleid);
            $this->assign("uprolename", $uprolename);

            //获取顶级菜单
            $roleup_list = Role::all(function($query){
                $query->field('id,rolename,uproleid')->where('state=1');
            });

            $result_tree = $this-> getTreeData($roleup_list,'tree','rolename','id','uproleid');
            $this->assign("roleup_list", $result_tree);

            $this->assign('breadcrumb', '添加角色');

            return $this->fetch();

    }

    //编辑角色
    public function editrole()
    {
        $request = Request::instance();

        //查看当前的记录
        $data = $request->param();
        $this->assign('id', $data['id']);
        $list = Db::query("select id,rolename,uproleid,comment from authority_role where id=?", [$data['id']]);
        if($list[0]['uproleid']){
            $list_up = Db::query("select rolename from authority_role where id=?", [$list[0]['uproleid']]);
            $rolename = $list_up[0]['rolename'];
        }else{
            $rolename = '顶级';
        }


        //获取顶级菜单
        //获取顶级菜单
        $roleup_list = Role::all(function($query){
            $query->field('id,rolename,uproleid')->where('state=1');
        });

        $result_tree = $this->getTreeData($roleup_list,'tree','rolename','id','uproleid');
        $this->assign("roleup_list", $result_tree);
        $this->assign('breadcrumb', '编辑角色');

        return $this->fetch('addrole', [
            'uproleid' => $list[0]['uproleid'],
            'rolename' => $list[0]['rolename'],
            'uprolename' => $rolename,
            'list' => $list[0]
        ]);
    }




    // 设置权限
    public function setrole()
    {
        $request = Request::instance();
        if ($request->isPost()) {

            $data = $request->param();

            $roleid = $data["id"];
           // $menuids = rtrim($data["chkids"], ",");
            $menuidsarray = $data['rule_ids'];

            if(empty($menuidsarray)){
                return $this->error('请选择权限');
            }

            //获取原有角色名称
            $old_string = '(';
            $rolemenu = DB::name('authority_rolemenu')->where(['roleid'=>$roleid])->select();
            foreach($rolemenu as $key=>$val){

                //获取现有角色
                $menu = DB::name('authority_menu')->field('menuname')->where(['id'=>$val['menuid']])->find();
                $old_string .= $menu['menuname'].',';
            }
            $old_string .= ')';


            $insertvalue = "";
            $new_string = '(';
            foreach ($menuidsarray as $item) {
                $insertvalue .= "(" . $roleid . "," . $item . "),";

                //获取现有角色
                $menu = DB::name('authority_menu')->field('menuname')->where(['id'=>$item])->find();
                $new_string .= $menu['menuname'].',';

            }
            $new_string .= ')';

            Db::execute("delete from authority_rolemenu WHERE roleid=?", [$roleid]);
            Db::execute("insert into `authority_rolemenu` (`roleid`,`menuid`) values" . rtrim($insertvalue, ","));


            //添加日志
            $model = new Rolemenu();
            $data = [
                'menuid' => $new_string
            ];
            $old_data = [
                'menuid' => $old_string
            ];
            Base::save_admin_log($this->userId,$model,'edit',$roleid,$data,$old_data);

            return $this->success('设置成功', url('authority/rolelist'));

        }

        $data = $request->param();
        $id = $data['id'];

        //获取该角色的现有权限
        $sql = "select menuid from authority_rolemenu where roleid=?";
        $groupdata = Db::query($sql,[$id]);

        //获取该角色的上一级
        $uproleid = DB::name('authority_role')->field('uproleid')->where("id=?",[$id])->find();

        if($uproleid['uproleid'] == 0){

            $sql = "select authority_menu.* from authority_menu LEFT JOIN `authority_rolemenu` ON authority_rolemenu.`menuid` = authority_menu.`id` and authority_rolemenu.`roleid` = ?  where authority_menu.state='1' order by upmenuid,level asc ";
            $data = Db::query($sql,[$id]);
        }else{
            $sql = "select authority_menu.*,authority_rolemenu.id as rolemenuid from authority_menu LEFT JOIN `authority_rolemenu` ON authority_rolemenu.`menuid` = authority_menu.`id`   where authority_menu.state='1' and authority_rolemenu.`roleid` = ? order by upmenuid,level asc ";
            $data = Db::query($sql, [$uproleid['uproleid']]);
        }
        //print_r(DB::name("authority_menu")->getLastSql());

        $list = $this->getTreeData($data,'level');
           // print_r($list);
        $this->assign("rule_data", $list);

         $this->assign("group_data", array_column($groupdata,'menuid'));
         $this->assign("id", $id);
        $this->assign('breadcrumb', '设置权限');
        $cancel_url = "authority/rolelist";
        $this->assign('cancel_url', $cancel_url);
         return $this->fetch();
    }

    /*****************管理员管理*********************/


    //管理员列表
    public function admin_list(){

        $where = "admin.is_deleted=1";
        $name = '';
        if ($this->request->isGet()) {
            $data = $this->request->param();

            if (isset($data['name']) && trim($data['name'])) {

                $name = trim($data['name']);
                $where  .= " and (admin.name like '%{$name}%' or admin.admin_name like '%{$name}%')";

            }
        }

        $this->assign("name", $name);


        $sql = "
            select admin.*,authority_role.rolename,doctor_department.department as depart_name from admin
            left join authority_role ON authority_role.id=admin.roleid
            left join doctor_department ON doctor_department.id=admin.depart_id
            where {$where}
        ";
        $list = Db::query($sql);
        $this->assign("list", $list);

        $count = DB::name('admin')->where($where)->count();

        $this->assign("count", $count);
        $this->assign('breadcrumb', '后台账号列表');
        return $this->fetch();
    }



    //新增
    public function add_admin()
    {

            //获取角色
            $sql = "select * from authority_role where state<2";
            $roles = Db::query($sql);

        $sql = "select * from doctor_department where is_deleted=1";
        $departs = Db::query($sql);

            $this->assign('roles', $roles);
            $this->assign('departs', $departs);
        $this->assign('breadcrumb', '添加管理员');

            return $this->fetch();

    }

    //编辑商品
    public function edit_admin()
    {
        $request = Request::instance();

        //查看当前的记录
        $data = $request->param();
        $this->assign('id', $data['id']);
        $list = Db::query("select * from admin where admin_id=?", [$data['id']]);
        $this->assign('list', $list[0]);

        //获取角色
        $sql = "select * from authority_role where state<2";
        $roles = Db::query($sql);
        $sql = "select * from doctor_department where is_deleted=1";
        $departs = Db::query($sql);

        $this->assign('roles', $roles);
        $this->assign('departs', $departs);
        $this->assign('breadcrumb', '编辑详情');

        return $this->fetch('add_admin', [

        ]);
    }


    //退出
    public function logout(){
        session(null);
        return $this->success("退出成功", url("login/index"));
    }


    /*****************管理员管理*********************/

    /***添加部门****/
    public function department(){

        //搜索

        $option['is_deleted'] = ['=', 1];
        //$option['doctor_id'] = $this->doctor->id;

        //默认年月日
        $pageQuery = [];

        if ($this->request->isGet()) {
            $data = $this->request->param();

            if (isset($data['name']) && trim($data['name'])) {
                $option['department'] = array('like', '%' . trim($data['name']) . '%');
                $pageQuery['query']['name'] = trim($data['name']);

            }

        }
        $this->assign('search', isset($pageQuery['query']) ? $pageQuery['query'] : '');
        $departs = DB::name('doctor_department')
            ->where($option)
            ->order('create_time desc')
            ->paginate(false, false, $pageQuery)
            ->each(function($item,$key){
                $count_admin = DB::name('doctor')->join("doctor_department","doctor.depart_id=doctor_department.id")->where("doctor.depart_id={$item['id']}")->count();
                $item['count_admin'] = $count_admin;
                return $item;
            });

        $this->assign('list', $departs);

        $count = DB::name('doctor_department')->where($option)->count();
        $this->assign('count', $count);

        $this->assign('breadcrumb', '部门管理');
        return $this->fetch();
    }


    /**
     *添加部门
    **/

    public function add_department(){

        $this->assign('breadcrumb', '新建部门');
        return $this->fetch();
    }

    public function edit_department(){
        $data = $this->request->param();
        $this->assign('id', $data['id']);
        $list = Db::query("select * from doctor_department where id=?", [$data['id']]);
        $this->assign('list', $list[0]);
        $this->assign('breadcrumb', '编辑部门');
        return $this->fetch('add_department');
    }




}